package com.um.swing.core.thread;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import com.um.swing.bean.ImageItem;
import com.um.swing.core.ImageJoinCore;
import com.um.swing.core.event.ExportEvent;

import java.awt.*;
import java.io.File;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 名称：拼板导出 线程
 * 创建人：袁泉
 * 创建时间：2022年05月04日15:00:24
 */
public class ExportRunable implements Runnable {
    private List<ImageItem> data;
    private String targetPath;
    private ExportEvent finishCallback;
    private CountDownLatch countDownLatch;
    private boolean stopExport = false;

    public ExportRunable(List<ImageItem> data, String targetPath, CountDownLatch countDownLatch, ExportEvent finishCallback) {
        this.data = data;
        this.targetPath = targetPath;
        this.finishCallback = finishCallback;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 0; i < data.size(); i++) {
            if (stopExport) {
                return;
            }
            ImageItem prvItem = null;
            ImageItem item = data.get(i);
            if (i == 0 || i % 2 == 0) {
                finishCallback.onItemFinish(item, "预处理", false);
                continue;
            } else {
                prvItem = data.get(i - 1);
            }
            if (!item.isOverPoint() || !prvItem.isOverPoint()) {
                finishCallback.onItemFinish(item, "标点不完整，无法拼版", true);
                continue;
            }
            boolean isError = false;
            String info = "";
            try {
                Image image = ImageJoinCore.imageJoin(prvItem, item, null);
                ImgUtil.write(image, new File(targetPath + File.separator + i + ".png"));
                info = "导出成功";
            } catch (Exception e) {
                e.printStackTrace();
                isError = true;
                info = "导出失败，发生错误：" + e.getMessage();
            }
            finishCallback.onItemFinish(item, info, isError);
        }
        countDownLatch.countDown();
    }

    public void stopExport() {
        this.stopExport = true;
    }
}
